package com.hwadee.springboot_lx.service;

import org.springframework.stereotype.Service;

import java.io.IOException;
@Service
public class DataService {
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String DATABASE_NAME = "my_database";

    public void backupDatabase(String filePath) throws IOException {
        // 创建备份文件的路径
        String command = String.format("mysqldump -u %s -p%s %s > %s", USERNAME, PASSWORD, DATABASE_NAME, filePath);

        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor(); // 等待命令执行完毕

            if (exitCode == 0) {
                System.out.println("Database backup successful.");
            } else {
                System.out.println("Database backup failed.");
            }
        } catch (InterruptedException e) {
            // 处理异常
            e.printStackTrace();
            Thread.currentThread().interrupt(); // 恢复中断状态
        }
    }
    public void restoreDatabase(String filePath) throws IOException {
        // 创建恢复数据库的命令
        String command = String.format("mysql -u %s -p%s %s < %s", USERNAME, PASSWORD, DATABASE_NAME, filePath);

        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor(); // 等待命令执行完毕

            if (exitCode == 0) {
                System.out.println("Database restore successful.");
            } else {
                System.out.println("Database restore failed.");
            }
        } catch (InterruptedException e) {
            // 处理异常
            e.printStackTrace();
            Thread.currentThread().interrupt(); // 恢复中断状态
        }
    }
}
